package com.qunar.dyds.service;

import java.util.concurrent.TimeoutException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.qunar.base.meerkat.cache.CacheClient;
import com.qunar.base.meerkat.cache.CacheException;
import com.qunar.base.meerkat.monitor.util.RequestUtil;
import com.qunar.common.admin.service.AbstractService;

@Service
public class RequestService extends AbstractService {

    @Resource(name = "cacheClient")
    private CacheClient cache;

    public boolean isSpam(HttpServletRequest request, String keyPrefix, int max, int expire) {

        String ip = RequestUtil.getIP(request);
        logger.debug("isSpam Start. ip={}", ip);

        String key = keyPrefix + "_" + ip;

        boolean ret = false;

        try {
            ret = (cache.increment(key, 1, 1, 3000, expire) > max);
        } catch (CacheException e) {
            logger.error("Cache exception, e={}", e);
        } catch (InterruptedException e) {
            logger.error("Interrupted exception, e={}", e);
        } catch (TimeoutException e) {
            logger.error("Timeout exception, e={}", e);
        }

        logger.debug("isSpam End.");

        return ret;
    }
}
